from common.intercept import AbstractApiInterceptor, AbstractApiBeforeInterceptor, AbstractApiAfterInterceptor
from config.settings import value
from utils.http_visit import HttpMethod, ApiRequest


def api(
        path: str,
        method: HttpMethod = HttpMethod.GET,
        base_url=value('${server.url}'),
        headers=None,
        form=None,
        json=None,
        interceptor: AbstractApiInterceptor = None
):
    def do_request(fun):
        def wrapper(*args, **kwargs):
            req = ApiRequest(url=base_url + path, request_method=method, form_data=form, json_data=json,
                             headers=headers)
            if interceptor and isinstance(interceptor, AbstractApiBeforeInterceptor):
                req = interceptor.before_intercept(req)
            res = req.do_send()
            if interceptor and isinstance(interceptor, AbstractApiAfterInterceptor):
                req, res = interceptor.after_intercept(req, res)
            return res

        return wrapper

    return do_request
